﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Text;
using System.Web.Caching;
using System.Web;
using Xpus.YouYTube.Data;

namespace Xpus.YouYTube.Utility
{
	/// <summary>
	/// 实现敏感词替换功能。
	/// </summary>
	public static class TSensitiveWordManager
	{
		/// <summary>
		/// 对给定的字符串进行敏感词替换。
		/// </summary>
		/// <param name="source">待替换的字符串。</param>
		/// <returns>替换了敏感词的字符串。</returns>
		public static string Repleace(string source)
		{
			Dictionary<string, string> list = GetSensitiveWords();
			StringBuilder sb = new StringBuilder(source);

			foreach (var key in list.Keys)
			{
				sb.Replace(key, list[key]);
			}

			return sb.ToString();
		}

		const string CacheKey = "Xpus.YouYTube.SensitiveWords";

		/// <summary>
		/// 加载敏感词替换列表。
		/// </summary>
		/// <returns></returns>
		private static Dictionary<string, string> GetSensitiveWords()
		{
			// 尝试从缓存中读取
			Dictionary<string, string> swlist = (Dictionary<string, string>)HttpContext.Current.Cache[CacheKey];

			if (swlist != null)
				return swlist;

			// 从数据库中加载
			swlist = new Dictionary<string, string>();

			using (TDataContext db = new TDataContext())
			{
				var sws = db.TSensitiveWords;

				foreach (var s in sws)
				{
					swlist.Add(s.Source, s.Destination);
				}
			}

			// 放入缓存
			SqlCacheDependency depend = new SqlCacheDependency("yyt", "TSensitiveWord");
			HttpContext.Current.Cache.Insert(CacheKey, swlist, depend);

			return swlist;
		}
	}
}
